<?php
/**
 * @ClassName: Team
 * @Description: TODO
 * @author: gydtrade
 * @Date: 2025-10-16 13:50
 * @Version: V1.0.0
 */

namespace app\api\controller;

use app\common\logic\agent\TeamLogic;
use app\common\logic\MemberLogic;
use app\common\model;

class Team extends Api
{
    protected $noNeedLogin = ['agentLevels'];

    /**
     * 统计数据
     * @return \think\response\Json
     */
    function index()
    {
        $member = $this->userInfo;
        $teamNum = MemberLogic::getTeam($member);
        $firstTeam = MemberLogic::getFirst($member);
        $scondTeam = MemberLogic::getScond($member);

        $result = [
            'firstTeam' => $firstTeam,
            'scondTeam' => $scondTeam,
            'teamNum' => $teamNum,
        ];

        return json(['code' => 1, 'data' => $result]);
    }

    /**
     * 代理等级列表
     * @return \think\response\Json
     */
    function agentLevels()
    {
        $list[] = [
            'label' => '代理等级',
            'value' => 0,
        ];

        $agentLevels = model\AgentLevel::order('level asc')->select();

        foreach ($agentLevels as $level) {
            $list[] = [
                'label' => $level['name'],
                'value' => $level['level'],
            ];
        }

        return json(['code' => 1, 'data' => $list]);
    }

    /**
     * 我的团队列表
     * @return \think\response\Json
     */
    function getMyTeam()
    {
        $type = input('type', '0');
        $agent_level = input('agent_level', -1);
        $keyword = input('keyword', '');
        $skip = input('skip', 0);
        $limit = input('limit', 10);

        $member_id = $this->member_id;

        $where = [];
        $where[] = ['status', '=', 1];

        if ($agent_level != -1) {
            $where[] = ['agent_level', '=', $agent_level];
        }

        if ($keyword) {
            $where[] = ['id|nickname|real_name|mobile|link_name|link_phone', 'like', '%' . $keyword . '%'];
        }
        switch ($type) {
            case '1':
                //直推团队
                $where[] = ['first_leader', 'eq', $member_id];
                break;
            case '2':
                //间推团队
                $where[] = ['relation', 'like', '%,' . $member_id . ',%'];
                $where[] = ['id', '<>', $member_id];
                $where[] = ['first_leader', '<>', $member_id];
                break;
            default:
                //全部团队
                $where[] = ['relation', 'like', '%,' . $member_id . ',%'];
                $where[] = ['id', '<>', $member_id];
                break;
        }
        $list = TeamLogic::getMySubordinate($where, $skip, $limit);

        foreach ($list as $k => $li) {
            $list[$k]['avatar'] = $li['avatar'] ? replace_url($li['avatar']) : replace_url('/static/images/logo.png');
            $list[$k]['agent_level_str'] = 'J' . $li['agent_level'];
        }

        return json(['code' => 1, 'data' => $list]);
    }

}